package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.train.MoreActivities.MoreSpecialActivity;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.opengl.GLSurfaceView.Renderer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

public class StationMapActivity extends Activity implements OnGestureListener, Renderer{
	private WebView stationMapWebView, stationHeaderWebView;
	private WebViewClient clientForMap;
	private int line = 0;
	private ArrayList<ImageView> line_list;
	private String station_id, handle_id;
	private GestureDetector mGestureDetector;

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState){
        
		super.onCreate(savedInstanceState);
        setContentView(R.layout.stationmap);
        line_list = new ArrayList<ImageView>();
        stationMapWebView = (WebView) findViewById(R.id.stationMapWebView);
        stationHeaderWebView = (WebView) findViewById(R.id.stationHeaderWebView);
        mGestureDetector = new GestureDetector(this);
        
        stationHeaderWebView.getSettings().setJavaScriptEnabled(true);
        stationHeaderWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsConfirm(WebView view, final String url,
            		String message, final JsResult result) {
            	new AlertDialog.Builder(view.getContext())
                .setMessage(message)
                .setPositiveButton(android.R.string.ok,
                        new AlertDialog.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int which)
                            {
                            	result.confirm();
                            }
                        })
                .setNegativeButton(android.R.string.cancel,
		                new AlertDialog.OnClickListener()
		                {
		                    public void onClick(DialogInterface dialog, int which)
		                    {
		                    	result.cancel();
		                    }
		                })
                .setCancelable(false)
                .create()
                .show();

            return true;
            }
        });
		stationHeaderWebView.setWebViewClient(new WebViewClient(){
			@Override
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
				if(url.contains("!")){
					String[] values = url.split("!");
					if(values[1].equals("app")){
						if(values[2].equals("live")){
							Intent intent = new Intent(getBaseContext(), AllBoardActivity.class);
							startActivity(intent);
						}
						else if(values[2].equals("enjoy")){
							Intent intent = new Intent(getBaseContext(), MoreSpecialActivity.class);
							startActivity(intent);
						}
					}
					else if(values[1].equals("board")){
						Intent intent = new Intent(getBaseContext(), StationBoardActivity.class);
						TrainTravelActivity tab = (TrainTravelActivity) getParent();
				        TrainTravelActivity.tabHost.setCurrentTab(3);
						tab.onTabChanged("Tab4");
						intent.putExtra("board_id", values[2]);
						StationIdAsynkTask task = new StationIdAsynkTask();
						String[] params = new String[]{ ServerURL.stationIdFromBoard, "board_id", values[2]};
						task.execute(params);
						intent.putExtra("station_id", station_id);
						((FavoriteActivity) tab.getCurrentActivity()).startChildActivity("StationBoard", intent);
					}
					else if(values[1].equals("web")){
						Intent intent = new Intent(Intent.ACTION_VIEW); 
						Uri uri = Uri.parse(values[2]); 
						intent.setData(uri); 
						startActivity(intent);
					}
				}
			}
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		stationHeaderWebView.loadUrl(ServerURL.headerWebView(Preferences.getValue(getBaseContext(), "device_token"),
				  					 						 Preferences.getValue(getBaseContext(), "user_id"),
				  					 						 Preferences.getValue(getBaseContext(), "version")));

		stationMapWebView.getSettings().setJavaScriptEnabled(true);
		stationMapWebView.getSettings().setSupportZoom(true);
		stationMapWebView.getSettings().setBuiltInZoomControls(true);
        registerForContextMenu(stationMapWebView);

		stationMapWebView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url){
				String[] values = url.split("s");
				int len = values.length;
				handle_id = values[len-1];
				openContextMenu(stationMapWebView);
				return true;
			}
		});
//		stationMapWebView.setOnTouchListener(new View.OnTouchListener() {
//		    @Override
//			public boolean onTouch(View v, MotionEvent event) {
//		    	return mGestureDetector.onTouchEvent(event);
//		    }
//		});

        addList();
//		image = (ImageView) findViewById(R.id.image);
//		SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.map);
//	    Picture picture = svg.getPicture();
//	    Drawable drawable = svg.createPictureDrawable();
//	    image.setImageDrawable(drawable);
	}

	public void addList(){
		line_list.add((ImageView)findViewById(R.id.line0));
		line_list.add((ImageView)findViewById(R.id.line1));
		line_list.add((ImageView)findViewById(R.id.line2));
		line_list.add((ImageView)findViewById(R.id.line3));
		line_list.add((ImageView)findViewById(R.id.line4));
		line_list.add((ImageView)findViewById(R.id.line5));
		line_list.add((ImageView)findViewById(R.id.line6));
		line_list.add((ImageView)findViewById(R.id.line7));
		line_list.add((ImageView)findViewById(R.id.line8));
		line_list.add((ImageView)findViewById(R.id.line9));
		line_list.add((ImageView)findViewById(R.id.line10));
		line_list.add((ImageView)findViewById(R.id.line11));
		line_list.add((ImageView)findViewById(R.id.line12));
		line_list.add((ImageView)findViewById(R.id.line13));
		line_list.add((ImageView)findViewById(R.id.line14));
		line_list.add((ImageView)findViewById(R.id.line15));
		setWebView(0);
	}
	
	public void setWebView(int line){
		// TODO
		ImageView temp;
		for(int i = 0 ; i <line_list.size(); i++){
			temp = line_list.get(i);
			temp.setImageResource(R.drawable.ico_page_off);
		}
		temp = line_list.get(line);
		temp.setImageResource(R.drawable.ico_page_on);
		stationMapWebView.loadUrl(ServerURL.setWebView(line));
	}
	

	private class StationIdAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject station = new JSONObject(result);
				station_id = station.get("station_id").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result.equals("favorite")){
				Toast.makeText(getBaseContext(), "이미 추가되어 있습니다.", Toast.LENGTH_SHORT).show();
			}
			else if(result.equals("success")){
				Toast.makeText(getBaseContext(), "관심역에 추가되었습니다.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
    @Override
	public boolean onTouchEvent(MotionEvent me) {
        return mGestureDetector.onTouchEvent(me);
    }
	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return false;
//        try {
//            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
//                return false;
//            
//            // right to left swipe
//            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
//                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//            	if(line < 15){
//            		line++;
//            		setWebView(line);
//            		return true;
//            	}
//            	else{
//            		return false;
//            	}
//            }
//            // left to right swipe
//            else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
//                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//            	if(line > 0){
//            		line--;
//            		setWebView(line);
//            		return true;
//            	}
//            	else{
//            		return false;
//            	}
//            }
//            else{
//            	return false;
//            }
//        } catch (Exception e) {
//    		return false;
//            
//        }

	}

	@Override
	public void onLongPress(MotionEvent arg0) {
		
	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		return false;
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// TODO Auto-generated method stub		
		
        clientForMap = new WebViewClient();

        stationMapWebView.setWebViewClient(clientForMap);
		stationMapWebView.loadUrl(ServerURL.setWebView(line));
		
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu ,View v, ContextMenu.ContextMenuInfo menuInfo){
		menu.setHeaderTitle(handle_id + "역");
		menu.add(Menu.NONE, 1, Menu.NONE, "관심역 추가");
		menu.add(Menu.NONE, 2, Menu.NONE, "취소");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	switch(item.getItemId()){
    	case 1:
    		UploadAsynkTask task = new UploadAsynkTask();
			String[] params = new String[]{ ServerURL.addFavoriteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id"),
					"station_id", handle_id};
			task.execute(params);
    		break;
    	case 2:
    		break;
    	}
		return false;
    	
    }


}
